package src.java.medium;

import java.util.ArrayList;
import java.util.List;

public class Solution102 {
    //    public List<List<Integer>> levelOrder(TreeNode root) {
//        if (root == null) return new ArrayList<>();
//        Queue<TreeNode> queue = new LinkedList<>();
//        queue.add(root);
//        List<List<Integer>> result = new ArrayList<>();
//        while (!queue.isEmpty()) {
//            int size = queue.size();
//            List<Integer> level = new ArrayList<>();
//            for (int i = 0; i < size; i++) {
//                TreeNode polled = queue.poll();
//                level.add(polled.val);
//                if (polled.left != null) queue.add(polled.left);
//                if (polled.right != null) queue.add(polled.right);
//            }
//            result.add(level);
//        }
//        return result;
//    }
    List<List<Integer>> result = new ArrayList<>();
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) return new ArrayList<>();
        dns(root, 1);
        return result;
    }
    public void dns(TreeNode node, int level) {
        if (node == null) return;
        int size = result.size();
        if (level > size) {
            List<Integer> levelList = new ArrayList<>();
            levelList.add(node.val);
            result.add(levelList);
        } else {
            result.get(level - 1).add(node.val);
        }
        dns(node.left, level + 1);
        dns(node.right, level + 1);
    }
}

//class Node {
//    int level;
//    TreeNode node;
//
//    public Node(int level, TreeNode node) {
//        this.level = level;
//        this.node = node;
//    }
//}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}